﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Data;

namespace SharpSoft.WPF.Converters
{
    /// <summary>
    /// 将其他对象转为bool值
    /// </summary>
    public class ToBooleanConverter : IValueConverter
    {
        /// <summary>
        /// 是否对转换结果取反
        /// </summary>
        public bool Negation { get; set; } = false;
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool result = true;
            //null 空字符串 数值0 转为false，其他情况为true
            if (value == null || value == DBNull.Value)
            {
                result = false;
            }
            else if (value is bool bo)
            {
                result = bo;
            }
            else if (value is string str && str == "")
            {
                result = false;
            }
            else if (value is IComparable comp)
            {
                result = (comp.CompareTo(0) != 0);
            }
            else if (value is Array array)
            {
                result = false;
                for (int i = 0; i < array.Rank; i++)
                {
                    var length = array.GetLength(i);
                    if (length > 0)
                    {
                        result = true;
                        break;
                    }
                }
            }
            else if (value is ICollection coll && coll.Count == 0)
            {
                result = false;
            }
            if (this.Negation)
            {
                result = !result;
            }
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
